// 评论自动回复
import puppeteer from "puppeteer";
import * as fs from "fs";
import * as mysql from "mysql2/promise";
import rivalList from "./blackList.js";

const username = "追光人";
const data = fs.readFileSync(`./cookie/${username}.json`, "utf8");
const cookie = JSON.parse(data);

let keyword = "";
keyword = process.argv.slice(2).join(" ") || "推荐";

const baseHref = "https://www.xiaohongshu.com";
let connection;

const dbConnect = async () => {
  connection = await mysql.createConnection({
    host: "127.0.0.1",
    user: "root",
    password: "wk051105",
    database: "sql_hongshu_electron",
  });
  console.log("数据库连接成功");

  // connection.end();
};

// 打开浏览器任务
const mainTask = async () => {
  await dbConnect();

  // 启动浏览器
  const browser = await puppeteer.launch({
    headless: false,
    defaultViewport: null,
    args: ["--no-default-browser-check"],
  });
  const context = await browser.createBrowserContext();
  context.setCookie(...cookie);
  // console.log(cookie);

  async function getList(listIndex) {
    // 每10条一取
    const start = listIndex * 10 + 109;
    const sql = "SELECT * FROM spider limit ?, ?";
    const params = [start, 10];
    const [results] = await connection.query(sql, params);
    // console.log(results);

    return results;
  }

  const openDetail = async (context, index, listIndex) => {
    const url =
      "https://www.xiaohongshu.com/explore/668544db000000001e0112f6?xsec_token=YBR3sayTTK73mHCcWutnDN89USGNr7JbrQKWPsx7TMPfU%3D&xsec_source=pc_creatormng";
    // const url = baseHref + "/" + list[index]?.path;
    // console.log(list[index]?.title);
    // console.log(list[index]?.name);
    // console.log(index);
    const detailPage = await context.newPage();
    await detailPage.goto(url);

    // 等待评论加载完成
    await detailPage.waitForSelector(".comments-el");

    // 判断是否追评过
    // 定位到上级评论 todo
    // 上级评论是谁 评论内容 todo
    await checkComments(detailPage);

    // const urlObj = new URL(url);
    // const keyword = urlObj.pathname.replace("/explore|search_result/", "");
    // const sql = "SELECT * FROM spider where path like ?";
    // const queryParams = [`%${keyword}%`];
    // const [results] = await connection.query(sql, queryParams);
    // console.log(queryParams);
    // console.log(results);
    // console.log(results.length);
    // console.log(results.length > 0);
    // if (results.length > 0) {
    //   console.log(
    //     `标题为：${list[index]?.title}的笔记已经评论过了，执行跳过`
    //   );
    //   console.log(url);
    // } else {
    // console.log(`标题为：${list[index]?.title}的笔记开始评论`);
    // console.log(url);

    // await detailPage.waitForSelector(".comments-el");
    // 发布
    // await inputContent(detailPage);
    // 保存已评论的路径
    // await saveCommentId(url);
    // }
    // console.log("");
    await new Promise((resolve) => setTimeout(resolve, 1000));
    // index++;

    // if (index === maxNum) {
    //   // 重新获取列表内容
    //   await new Promise((resolve) => setTimeout(resolve, 2000));

    //   detailPage.close();

    //   await new Promise((resolve) => setTimeout(resolve, 2000));
    //   console.log(`当前第${listIndex}页，开始执行翻页`);
    //   console.log("--------------------");
    //   listIndex++;

    //   await new Promise((resolve) => setTimeout(resolve, 2000));

    //   init(listIndex);
    // } else {
    //   await new Promise((resolve) => setTimeout(resolve, 2000));
    //   detailPage.close();
    //   await new Promise((resolve) => setTimeout(resolve, 2000));
    //   openDetail(context, index, listIndex);
    // }
  };

  // 获取评论
  const getComments = async (page) => {
    const comments = await page.$$eval(".parent-comment", (elements) => {
      return elements.map((item) => {
        const author = item.querySelector(".author a")?.textContent || "";
        const content = item.querySelector(".note-text")?.textContent || "";
        return { author, content };
      });
    });

    return comments;
  };

  // 检查评论
  const checkComments = async (page) => {
    const comments = await getComments(page);

    // 上级用户名单
    const userlist = ["南京登科寄宿备考自习室"];

    let commentIndex = comments.findIndex((item) =>
      userlist.includes(item.author)
    );
    // console.log(commentIndex);

    // 当前页找到目标上级评论
    if (commentIndex > -1) {
      // console.log("找到");

      const replayBtn = await page.waitForSelector(
        `.parent-comment:nth-child(${commentIndex + 1}) .reply`
      );
      await new Promise((resolve) => setTimeout(resolve, 1000));
      replayBtn.click();
      // console.log("点击了回复按钮");
      inputContent(page);
    } else {
      // 当前页未找到目标上级评论 则向下刷新评论
      // await checkComments(page);
      return null;
    }
  };

  const inputContent = async (page) => {
    const article =
      "①吃、住、学一站式备考基地\n②寄宿备考+择校规划+督学+模考+答疑\n③单人间/双人间/三人间/四人间\n④自营食堂，一天33元\n⑤提供住宿宽带➕健身/游泳➕意外保险➕床上六件套";
    await page.waitForSelector("div.content-edit");

    return new Promise(async (resolve) => {
      await new Promise((resolve) => setTimeout(resolve, 1000));

      await page.waitForSelector("p.content-input");

      await page.keyboard.sendCharacter(article);

      // 评论 并 提交
      const sumbit = await page.waitForSelector(".interactions button.submit");
      await new Promise((resolve) => setTimeout(resolve, 500));
      sumbit.click();
      resolve(0);
    });
  };

  // 记录到库
  const saveCommentId = async (url) => {
    // 插入
    const sql =
      "INSERT INTO spider (id, path, keyword, username) VALUES (0, ?, ?,?)";
    const newUrl = url.replace("https://www.xiaohongshu.com/", "");
    const addarams = [newUrl, keyword, username];
    const [results] = await connection.query(sql, addarams);
    // console.log('INSERT ID:', results);
    console.log("已评论并记录");
  };

  let list;
  const listIndex = 0;
  let maxNum;
  let index;
  const init = async (listIndex) => {
    // 执行任务
    list = await getList(listIndex);
    if (list.length > 0) {
      maxNum = list.length;
      index = 0;

      // 打开详情页
      await openDetail(context, index, listIndex);
    }
  };
  init(listIndex);
};

const close = async (browser) => {
  setTimeout(() => {
    browser.close();
  }, 1500);
};

mainTask();
// export { mainTask, close };
